<template>
  <el-tree-select
    lazy
    filterable
    check-strictly
    v-model="model"
    node-key="regionCode"
    :load="handleLoad"
    :data="regionData"
    :default-expanded-keys="expandedKeys"
    :filter-method="filterMethod"
    @clear="handleClear"
    :props="{
      value: 'regionCode',
      label: 'regionName',
      isLeaf: 'hasChildren',
      children: 'children',
    }"
  />
</template>

<script lang="ts" setup>
import { ref, watchEffect } from "vue";
import { dictRegionApi } from "@/api/region/os-dict-region/index";
import type { DictRegionModel } from "@/api/region/os-dict-region/types";
import type Node from "element-plus/es/components/tree/src/model/node";
import { extractIdsOrCodes } from "@/utils";

const model = defineModel<string>();
// 默认展开节点
const expandedKeys = ref<string[]>([]);

// 获取默认展开节点
const getExpandedKeys = () => {
  dictRegionApi.findByCode({ regionCode: model.value }).then(({ data }) => {
    const region = extractIdsOrCodes(data);
    expandedKeys.value = region.regionCodes;
  });
};
// 根据地区编码查询地区信息
watchEffect(
  () => model.value && !expandedKeys.value.length && getExpandedKeys(),
);

const regionData = ref<DictRegionModel[]>([]);
// 过滤树形选择
const filterMethod = (value: string) => {
  dictRegionApi
    .findList({
      likeRegionName: value,
    })
    .then(({ data }) => {
      regionData.value = data.results.map((item) => {
        item.hasChildren = !item.hasChildren;
        return item;
      });
    });
};

// 清除树形选择
const handleClear = () => {
  expandedKeys.value = [];
};

// 树形选择懒加载
const handleLoad = (node: Node, resolve: (data: DictRegionModel[]) => void) => {
  dictRegionApi
    .findList({
      parentId: node.data.regionId,
    })
    .then(({ data }) => {
      const region = data.results.map((item) => {
        item.hasChildren = !item.hasChildren;
        return item;
      });
      !node.data.regionId && (regionData.value = region);
      resolve(region);
    });
};
</script>
